from flask import Flask, render_template, jsonify, request
import json
import os

app = Flask(__name__)

# 数据文件路径
DATA_FILE = 'data.json'

def load_data():
    """加载数据"""
    if os.path.exists(DATA_FILE):
        with open(DATA_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    return []

def save_data(data):
    """保存数据"""
    with open(DATA_FILE, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

@app.route('/')
def index():
    """主页"""
    return render_template('index.html')

@app.route('/api/questions')
def get_questions():
    """获取所有题目"""
    questions = load_data()
    return jsonify(questions)

@app.route('/api/questions', methods=['POST'])
def add_question():
    """添加新题目"""
    data = request.json
    questions = load_data()
    
    # 生成新的ID
    new_id = 1
    if questions:
        new_id = max(q['id'] for q in questions) + 1
    
    new_question = {
        'id': new_id,
        'question': data.get('question', ''),
        'parse': data.get('parse', ''),
        '关联题目': data.get('关联题目', [])
    }
    
    questions.append(new_question)
    save_data(questions)
    
    return jsonify(new_question)

@app.route('/api/questions/<int:question_id>', methods=['PUT'])
def update_question(question_id):
    """更新题目"""
    data = request.json
    questions = load_data()
    
    for question in questions:
        if question['id'] == question_id:
            question['question'] = data.get('question', question['question'])
            question['parse'] = data.get('parse', question['parse'])
            question['关联题目'] = data.get('关联题目', question['关联题目'])
            save_data(questions)
            return jsonify(question)
    
    return jsonify({'error': 'Question not found'}), 404

@app.route('/api/questions/<int:question_id>', methods=['DELETE'])
def delete_question(question_id):
    """删除题目"""
    questions = load_data()
    questions = [q for q in questions if q['id'] != question_id]
    save_data(questions)
    return jsonify({'success': True})

if __name__ == '__main__':
    # 如果数据文件不存在，创建示例数据
    if not os.path.exists(DATA_FILE):
        sample_data = [
            {
                "id": 1,
                "question": "两数之和",
                "parse": "使用哈希表存储已经遍历过的数字，时间复杂度O(n)",
                "关联题目": ["三数之和", "四数之和"]
            },
            {
                "id": 2,
                "question": "反转链表",
                "parse": "使用三个指针：prev、current、next，迭代反转链表",
                "关联题目": ["反转链表II", "K个一组反转链表"]
            }
        ]
        save_data(sample_data)
    
    app.run(debug=True, host='0.0.0.0', port=5001)